<template>
  <div>
    <h2 style="margin-left: 2%">当前只支持json文件的读取</h2>
    <el-upload
      ref="upload"
      action="alert"
      :auto-upload="false"
      :file-list="uploadList"
      :on-change="loadJsonFromFile"
      accept="json"
      class="upload-demo"
      style="margin-left: 2%"
    >
      <el-button slot="trigger" size="medium" type="primary" >选取文件</el-button>
      <el-button
        size="medium"
        style="margin-top: 10px;margin-left: 2%"
        type="success"
        v-loading.body.lock="fullscreenLoading"
        @click="submit"
      >上传</el-button>
    </el-upload>
    <h2 style="margin-top: 2%; margin-left: 2%">JSON文件详情</h2>
    <JsonView
      :value = "importJsonData"
      :expand-depth = 5
      copyable
      boxed
      sort
      :expanded = true
    />
  </div>
</template>
<script>
import JsonView from 'vue-json-viewer'
export default {
  name: 'ServiceConfig',
  components: { JsonView },
  data() {
    return {
      fullscreenLoading: false,
      uploadList: [],
      importJsonData: {}
    }
  },
  methods: {
    loadJsonFromFile(file, fileList) {
      this.uploadList = fileList
    },
    submit() {
      this.fullscreenLoading = true
      setTimeout(() => {
        const file = this.uploadList[0]
        const reader = new FileReader()
        // abort none 中断读取
        // readAsBinaryString file 将文件读取为二进制码，通常我们将它传送到后端，后端可以通过这段字符串存储文件
        // readAsDataURL file 将文件读取为 DataURL，一段以 data: 开头的字符串，这段字符串的实质就是 Data URL，Data URL是一种将小文件直接嵌入文档的方案。这里的小文件通常是指图像与 html 等格式的文件
        // readAsText file, [encoding] 将文件读取为文本，读取的结果即是这个文本文件中的内容
        reader.readAsText(file.raw)
        // onabort 中断时触发
        // onerror 出错时触发
        // onload 文件读取成功完成时触发
        // onloadend 读取完成触发，无论成功或失败
        // onloadstart 读取开始时触发
        // onprogress 读取中
        reader.onload = (e) => {
          // 读取文件内容
          const fileString = e.target.result
          this.importJsonData = JSON.parse(fileString)
        }
        this.fullscreenLoading = false
        this.$notify({
          title: 'Success',
          message: 'Stop Successfully',
          type: 'success',
          duration: 2000
        })
      }, 1000)
    }
  }
}

</script>
